package com.lxb.myforum.controller

import java.io.IOException

import javax.imageio.ImageIO
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import javax.servlet.http.HttpSession
import javax.validation.Valid

import com.lxb.myforum.base.BaseService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.core.AuthenticationException
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.web.WebAttributes
import org.springframework.stereotype.Controller
import org.springframework.ui.ModelMap
import org.springframework.validation.BindingResult
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping

import com.lxb.myforum.commons.ImageCode
import com.lxb.myforum.pojo.User
import com.lxb.myforum.service.UserService

/**
 *
 * @author lxb
 */
@Controller
class HomeController @Autowired constructor(
        private val imageCode: ImageCode,
        private val userService: UserService
) : BaseService() {

    @GetMapping(value = ["/", "/index"])
    fun index(): String {
        println("Go index page")
        return "/index"
    }

    @GetMapping(value = ["/login"])
    fun login(session: HttpSession): String {
        val `object` = SecurityContextHolder.getContext().authentication.principal
        if (`object` is User) {
            return "redirect:/index"
        }
        logger.info(`object`)
        println("go login page")
        return "/login"
    }

    @PostMapping(value = ["/loginFail"])
    fun loginFail(request: HttpServletRequest): String {
        val e = request.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION) as AuthenticationException
        println("login error page")
        request.setAttribute("error", e.message)
        return "/login"
    }

    @GetMapping(value = ["/register"])
    fun registerPage(map: ModelMap): String {
        val user = User()
        map["user"] = user
        return "/register"
    }

    @PostMapping(value = ["/register"])
    fun registerAction(session: HttpSession, verifyCode: String, @Valid user: User, bindingResult: BindingResult,
                       map: ModelMap): String {
        val vcString = session.getAttribute("VERIFY_CODE") as String
        var hasError = false
        if (!vcString.contentEquals(verifyCode)) {
            println("验证码错误")
            hasError = true
            map["verifyCodeError"] = "验证码错误"
        }
        println(user)
        println(verifyCode)
        if (bindingResult.hasErrors()) {
            hasError = true
            map["user"] = user
        }
        return if (hasError) {
            "/register"
        } else {
            userService.saveUser(user)
            "redirect:/login"
        }
    }

    @GetMapping(value = ["/verifyCode"])
    fun verifyCode(request: HttpServletRequest, response: HttpServletResponse) {
        try {
            ImageIO.write(imageCode.getImage(request), "JPEG", response.outputStream)
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
}
